package borge.web.teamspirit.client.page.team.widgets;

import java.util.List;

import borge.web.teamspirit.client.SessionData;
import borge.web.teamspirit.client.TeamSpirit;
import borge.web.teamspirit.client.data.Comment;
import borge.web.teamspirit.client.data.Match;
import borge.web.teamspirit.client.data.Serie;
import borge.web.teamspirit.client.data.SerieStats;
import borge.web.teamspirit.client.data.TeamPlayer;
import borge.web.teamspirit.client.data.TeamSerieInfo;
import borge.web.teamspirit.client.interfaces.PersistentData;
import borge.web.teamspirit.client.interfaces.ServerCallbackHandler;
import borge.web.teamspirit.client.interfaces.WidgetEventHandler;
import borge.web.teamspirit.client.interfaces.PersistentData.DataKey;
import borge.web.teamspirit.client.page.shared.widgets.ShowCommentsWidget;
import borge.web.teamspirit.client.page.team.TableUtil;
import borge.web.teamspirit.client.page.team.TokenData;
import borge.web.teamspirit.client.servercomm.DBQuery;
import borge.web.teamspirit.client.servercomm.DBQueryResults;
import borge.web.teamspirit.client.servercomm.ServerComm;
import borge.web.teamspirit.client.servercomm.DBQueryResults.Result;

import com.google.gwt.event.logical.shared.BeforeSelectionEvent;
import com.google.gwt.event.logical.shared.BeforeSelectionHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Hyperlink;

/**
 * Display a certain serie
 * @author andreas
 *
 */
public class ShowSerieWidget extends ShowTabbedDataWidget implements BeforeSelectionHandler<Integer>{

    private Serie iSerie;
    private TeamSerieInfo iSerieInfo;
    
    private String iNewSerieKey;
    private boolean iHasSerie;
    
    private static final int GENERAL_INDEX = 0;
    private static final int MATCHES_INDEX = 1;
    private static final int STATISTICS_INDEX = 2;
    private static final int DISCUSSION_INDEX = 3;
    
    private ServerCallbackHandler iServerHandler;
    private SerieStats iSerieStats;
    private ShowCommentsWidget iShowComments;
    //private List<VerticalPanel> iTabPanels;
    
    //private List<FlexTable> iTabTables;
    
    private static final String[] iTabTitles = {
            TeamSpirit.getConstants().general(),
            TeamSpirit.getConstants().matches(),
            TeamSpirit.getConstants().statistics(),
            TeamSpirit.getConstants().discussion()};
    
    
    public ShowSerieWidget(WidgetEventHandler aEventHandler){
        
        super(aEventHandler, iTabTitles);
        
        iPanel.addBeforeSelectionHandler(this);
        iPanel.selectTab(0);
        initWidget(iPanel);
        
    }
    
    private void fillPanels(){
    	
    	fillGeneralTab();
    	fillMatchesTab();
    	fillDiscussionTab();
    	fillStatisticsTab();
    }
    
    private void fillGeneralTab(){
    	
    	int row = 0, column = 0;
    	
    	FlexTable table = iTabTables.get(GENERAL_INDEX);
    	
//    	table.setText(row, column++, iConstants.type());
//    	table.setText(row++, column--, iSerie.getLeague().iAssociationName);
    	
    	table.setText(row, column++, iConstants.sport() + ":");
    	table.setText(row++, column--, iSerieInfo.getSport());
    	
    	table.setText(row, column++, iConstants.association() + ":");
    	table.setText(row++, column--, iSerieInfo.getAssociationName());
    	
    	table.setText(row, column++, iConstants.type() + ":");
    	table.setText(row++, column--, "Serie play");
    	
    	table.setText(row, column++, iConstants.category() + ":");
    	table.setText(row++, column--, iSerie.getLeague().getCategory().name());
    	
    	table.setText(row, column++, iConstants.season() + ":");
    	table.setText(row++, column--, iSerie.getLeague().getSeason());
    	
    	table.setText(row, column++, iConstants.division() + ":");
    	table.setText(row++, column--, iSerie.getLeagueDivision().toString());
    	
    	String status = "Active";
    	if(iSerie.getPlacement() > 0)
    		status = "Finished";
    	else if(iSerie.getPlacement() < 0)
    		status = "Not started";
    	
    	table.setText(row, column++, iConstants.status() + ":");
    	table.setText(row++, column--, status);
    }
    
    private void fillMatchesTab(){
    	
    	if(iSerie.getMatches() == null)
    		return;
    	
    	int row = 0, column = 0;
    	FlexTable table = iTabTables.get(MATCHES_INDEX);
    	table.setCellPadding(2);
    	List<PersistentData> matches = iSerie.getMatches();

    	for(PersistentData pd : matches){
    		Match m = (Match)pd;
    		column = 0;
    		table.setText(row, column++, DateTimeFormat.getShortDateTimeFormat().format(m.getDateTime()));
    		String token = TokenData.assembleTeamToken(TokenData.SHOW, TokenData.MATCH, m.getEncodedKey());
        	table.setWidget(row, column++, new Hyperlink(m.getOpponents(), token));
        	table.setText(row, column++, "" + m.getOurScore() + " - " + m.getOpponentScore());
        	
        	row++;
    	}
    	
    	
    }
    
    private void fillStatisticsTab(){
    	
    	if(iSerieStats == null)
    		return;
    	
    	FlexTable table = iTabTables.get(STATISTICS_INDEX);
    	int row = 0, column = 0;
    	
    	row = TableUtil.fillSerieStats(table, iSerieStats, row);
		
		table.setText(row, column++, "-----");
		table.setText(row++, column--, "------");		
		
    	List<PersistentData> players = SessionData.getTeamPlayers();
    	
    	table.setText(row, column++, "Players");
    	table.setText(row, column++, "Points");
    	table.setText(row, column++, "Goals");
    	table.setText(row, column++, "Assists");
    	table.setText(row, column++, "Red cards");
    	table.setText(row++, column++, "Yellow cards");
    	
    	
    	
    	for(PersistentData pd : players){
    		TeamPlayer player = (TeamPlayer)pd;
    		SerieStats.SeriePlayerStats stats = iSerieStats.getSeriePlayerStats(player.getEncodedKey());
    		
    		if(stats != null){
    			column = 0;
    			
    			table.setText(row, column++, player.getPersonName());
    			table.setText(row, column++, Integer.toString(stats.iGoals + stats.iAssists));
    			table.setText(row, column++, Integer.toString(stats.iGoals));
    			table.setText(row, column++, Integer.toString(stats.iAssists));
    			table.setText(row, column++, Integer.toString(stats.iRedCards));
    			table.setText(row++, column, Integer.toString(stats.iYellowCards));
    		}
    		
    	}
    	
    }
    
    private void fillDiscussionTab(){
    
    	if(iSerie.getComments() == null)
    		return;
    	
    	if(iShowComments == null){
    		iShowComments = new ShowCommentsWidget(null);
    		iTabPanels.get(DISCUSSION_INDEX).add(iShowComments);	
    	}
    	
    	iShowComments.setAndDisplay(iSerie.getComments());
    	
    }

	@Override
	public void populateData(DBQueryResults results) {
		
		Result result = results.getResult(DataKey.SERIE);
		if(result != null){
			Serie serie = (Serie)result.getResultList().get(0);
			iSerie = serie;
			SessionData.sCurrentSerie = serie;
			iSerieInfo = SessionData.sCurrentTeam.getSerieInfoByKey(iNewSerieKey);
			iPanel.selectTab(0);
		}
		
		result = results.getResult(DataKey.MATCH);
		if(result != null){
			iSerie.setMatches(result.getResultList());
		}
		
		result = results.getResult(DataKey.COMMENT);
		
		if(result != null){
			iSerie.setComments(result.getResultList());
		}
		
		result = results.getResult(DataKey.SERIESTATS);
		
		if(result != null){
			iSerieStats = (SerieStats)result.getResultList().get(0);
		}
		
		fillPanels();
	}

	@Override
	public void requestServerData(ServerCallbackHandler aHandler) {
		
		iServerHandler = aHandler;
		DBQuery query = new DBQuery(DataKey.SERIE, Serie.class.getName());
		query.addFilter("iEncodedKey", DBQuery.EQUALS, "serieParam", "String", iNewSerieKey, null);
		ServerComm.getAllSerieData(query, aHandler);

				
	}

	@Override
	public boolean needsUpdate(String aData) {

		if(iSerie == null || !iSerie.getEncodedKey().equals(aData)){
			iNewSerieKey = aData;
			return true;
		}
		
		return false;
	}

	@Override
	public void onBeforeSelection(BeforeSelectionEvent<Integer> event) {

		int index = event.getItem();
		
		if(index == MATCHES_INDEX && iSerie.getMatches() == null){
			// fetch matches
			DBQuery query = new DBQuery(DataKey.MATCH, Match.class.getName());
			query.addFilter("iOwningSerieKey", DBQuery.EQUALS, "serieKey", "String", iSerie.getEncodedKey(), null);
			ServerComm.getObjectList(query, iServerHandler);
		}
		else if(index == STATISTICS_INDEX){
			
			DBQuery query = new DBQuery(DataKey.SERIESTATS, SerieStats.class.getName());
			query.addFilter("iDummy", DBQuery.EQUALS, "dummyParam", "String", iSerie.getEncodedKey(), null);
			ServerComm.getSerieStats(query, iServerHandler);
			
		}
		else if(index == DISCUSSION_INDEX && iSerie.getComments() == null){
			// fetch comments
			DBQuery query = new DBQuery(DataKey.COMMENT, Comment.class.getName());
			query.addFilter("iParentKey", DBQuery.EQUALS, "serieKey", "String", iSerie.getEncodedKey(), null);
			ServerComm.getObjectList(query, iServerHandler);
		}
		
	}


}

